<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>视频</title>
    <style>
        html, body { padding: 0; margin: 0; width: 100%; height: 100%;}
        #container {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
  <body>
    <h1>webrtc</h1>
    <video id="localVideo" playsinline autoplay muted></video>
    <video id="remoteVideo" playsinline autoplay></video>
    <div id="container"></div>
    <script type="text/javascript" src="socket.io.min.js"></script>
    <script type="text/javascript">
        async function init() {
            const localVideo = document.getElementById('localVideo');
            const remoteVideo = document.getElementById('remoteVideo');
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
            localVideo.srcObject = stream;
            localStream = stream;
            const peer1 = new RTCPeerConnection({});
            const peer2 = new RTCPeerConnection({});
            for (const track of localStream.getTracks()) {
              peer1.addTrack(track, localStream);
            }
            peer1.onicecandidate = (e) => {
              peer2.addIceCandidate(e.candidate)
            }
            peer2.onicecandidate = (e) => {
              peer1.addIceCandidate(e.candidate)
            }
            peer2.ontrack = (e) => {
              const remoteVideo = document.getElementById('remoteVideo');
                if (remoteVideo.srcObject !== e.streams[0]) {
                  remoteVideo.srcObject = e.streams[0];
                }
            }
            const offer = await peer1.createOffer({
              offerToReceiveAudio: 1,
              offerToReceiveVideo: 1
            });
            await peer1.setLocalDescription(offer);
            await peer2.setRemoteDescription(offer);
            const answer = await peer2.createAnswer();
            await peer1.setRemoteDescription(answer);
            await peer2.setLocalDescription(answer);
        }
        
        //init()
        
    </script>
  </body>
</html>
